import { useState, useEffect, useRef } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { debateApi, trainingApi } from '../services/api'
import type { DebateSession, DebateRound, DebateEvaluation, Question } from '../types'
import './DebatePanel.css'

interface DebatePanelProps {
  userId: string
  questionId?: string
  questionContent?: string
  questionOptions?: string[]
  onNavigate?: (tab: string) => void
}

type DebatePhase = 'select' | 'position' | 'debating' | 'evaluation'

const DebatePanel = ({ userId, questionId, questionContent, questionOptions, onNavigate }: DebatePanelProps) => {
  const [phase, setPhase] = useState<DebatePhase>('select')
  const [debateSession, setDebateSession] = useState<DebateSession | null>(null)
  const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null)
  const [userPosition, setUserPosition] = useState<string>('中立')
  const [userArgument, setUserArgument] = useState<string>('')
  const [isLoading, setIsLoading] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [evaluation, setEvaluation] = useState<DebateEvaluation | null>(null)
  const historyEndRef = useRef<HTMLDivElement>(null)

  // 加载题目（如果没有提供）
  useEffect(() => {
    if (!questionContent && questionId) {
      loadQuestion()
    } else if (questionContent) {
      setCurrentQuestion({
        question_id: questionId || 'debate_question',
        session_id: '',
        content: questionContent,
        options: questionOptions || [],
        type: 'case_study',
        difficulty: 'medium',
        knowledge_points: []
      })
      // 如果提供了题目内容，直接进入立场选择阶段
      setPhase('position')
    }
  }, [questionId, questionContent, questionOptions])

  // 滚动到底部
  useEffect(() => {
    if (historyEndRef.current) {
      historyEndRef.current.scrollIntoView({ behavior: 'smooth' })
    }
  }, [debateSession?.rounds])

  const loadQuestion = async () => {
    if (!questionId) return
    try {
      const question = await trainingApi.getQuestionById(questionId)
      setCurrentQuestion(question)
    } catch (error) {
      console.error('加载题目失败:', error)
    }
  }

  // 开始辩论
  const startDebate = async () => {
    if (!currentQuestion) return

    setIsLoading(true)
    try {
      // 设置超时，避免无限等待
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('启动超时')), 10000) // 10秒超时
      )
      
      const sessionPromise = debateApi.startDebate(
        userId,
        currentQuestion.question_id,
        currentQuestion.content,
        userPosition,
        currentQuestion.options || []
      )
      
      const session = await Promise.race([sessionPromise, timeoutPromise]) as any
      setDebateSession(session)
      setPhase('debating')
    } catch (error) {
      console.error('开始辩论失败:', error)
      alert('启动辩论失败，请检查网络连接或刷新页面重试')
    } finally {
      setIsLoading(false)
    }
  }

  // 提交论点
  const submitArgument = async () => {
    if (!debateSession || !userArgument.trim()) return

    setIsSubmitting(true)
    try {
      const result = await debateApi.submitArgument(
        debateSession.debate_id,
        userArgument.trim()
      )

      // 更新会话
      const updatedSession = await debateApi.getDebateSession(debateSession.debate_id)
      setDebateSession(updatedSession)

      // 清空输入
      setUserArgument('')

      // 如果是最后一轮，显示评估
      if (result.is_final_round || updatedSession.status === 'ended') {
        if (updatedSession.evaluation) {
          setEvaluation(updatedSession.evaluation)
          setPhase('evaluation')
        } else {
          // 获取评估
          const evalResult = await debateApi.evaluateDebate(debateSession.debate_id)
          setEvaluation(evalResult)
          setPhase('evaluation')
        }
      }
    } catch (error) {
      console.error('提交论点失败:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  // 结束辩论
  const endDebate = async () => {
    if (!debateSession) return

    setIsLoading(true)
    try {
      const result = await debateApi.endDebate(debateSession.debate_id)
      if (result.evaluation) {
        setEvaluation(result.evaluation)
        setPhase('evaluation')
      }
    } catch (error) {
      console.error('结束辩论失败:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 重新开始
  const restartDebate = () => {
    setDebateSession(null)
    setUserArgument('')
    setEvaluation(null)
    setPhase('position')
  }

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp)
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }

  return (
    <div className="debate-panel">
      {/* 选择立场阶段 */}
      {phase === 'position' && currentQuestion && (
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="position-selection"
        >
          <h2>选择你的立场</h2>
          <div className="question-preview">
            <h3>题目：</h3>
            <p>{currentQuestion.content}</p>
            {currentQuestion.options && currentQuestion.options.length > 0 && (
              <div className="question-options-preview">
                <h4>选项：</h4>
                <ul>
                  {currentQuestion.options.map((option, index) => (
                    <li key={index}>{option}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>
          <div className="position-options">
            <button
              className={`position-button ${userPosition === '支持' ? 'selected' : ''}`}
              onClick={() => setUserPosition('支持')}
            >
              ✅ 支持
            </button>
            <button
              className={`position-button ${userPosition === '反对' ? 'selected' : ''}`}
              onClick={() => setUserPosition('反对')}
            >
              ❌ 反对
            </button>
            <button
              className={`position-button ${userPosition === '中立' ? 'selected' : ''}`}
              onClick={() => setUserPosition('中立')}
            >
              ⚖️ 中立
            </button>
          </div>
          <button
            className="start-debate-button"
            onClick={startDebate}
            disabled={isLoading}
          >
            {isLoading ? '启动中...' : '开始辩论'}
          </button>
        </motion.div>
      )}

      {/* 辩论阶段 */}
      {phase === 'debating' && debateSession && (
        <div className="debate-container">
          <div className="debate-header">
            <h2>辩论训练：法律思维交锋</h2>
            <div className="debate-info">
              <span className="position-badge">立场：{debateSession.user_position}</span>
              <span className="round-badge">第 {debateSession.current_round} / 5 轮</span>
              <button
                className="end-debate-button"
                onClick={endDebate}
                disabled={isLoading}
              >
                结束辩论
              </button>
            </div>
          </div>

          <div className="question-display">
            <h3>📋 题目</h3>
            <p>{debateSession.question_content}</p>
            {debateSession.question_options && debateSession.question_options.length > 0 && (
              <div className="question-options">
                <h4>选项：</h4>
                <ul>
                  {debateSession.question_options.map((option, index) => (
                    <li key={index}>{option}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>

          {/* 辩论历史 */}
          <div className="debate-history">
            <h3>💬 辩论历史</h3>
            {debateSession.rounds.length === 0 ? (
              <div className="empty-history">
                <p>开始你的第一轮论证吧！</p>
                <p className="hint">
                  💡 <strong>新手友好提示：</strong>
                  <br />
                  不用担心不知道具体法条，你可以：
                  <br />
                  1. 先分析题目中的关键事实（谁、做了什么、结果如何）
                  <br />
                  2. 从常识和逻辑角度思考（如果是我，我会怎么判断？）
                  <br />
                  3. 说出你的想法，AI会引导你逐步深入
                  <br />
                  <br />
                  <em>记住：重点是思考过程，不是完美答案！</em>
                </p>
              </div>
            ) : (
              <div className="history-list">
                {debateSession.rounds.map((round: DebateRound) => (
                  <div key={round.round} className="history-item">
                    <div className="round-header">
                      <span className="round-number">第 {round.round} 轮</span>
                      <span className="round-time">{formatTime(round.timestamp)}</span>
                    </div>
                    
                    <div className="user-argument">
                      <div className="message-header">
                        <span className="user-avatar">👤</span>
                        <span className="message-label">你的论点</span>
                      </div>
                      <div className="message-content">{round.user_argument}</div>
                    </div>

                    <div className="ai-response">
                      <div className="message-header">
                        <span className="ai-avatar">{round.ai_role === '对手' ? '🤖' : '⚖️'}</span>
                        <span className="message-label">
                          {round.ai_role === '对手' ? 'AI对手' : 'AI法官'}
                        </span>
                      </div>
                      <div className="message-content">{round.ai_response}</div>
                    </div>
                  </div>
                ))}
                <div ref={historyEndRef} />
              </div>
            )}
          </div>

          {/* 输入区域 */}
          {debateSession.status === 'active' && (
            <div className="argument-input-section">
              <label>
                <strong>📝 输入你的论点（第 {debateSession.current_round + 1} 轮）</strong>
                <textarea
                  className="argument-input"
                  value={userArgument}
                  onChange={(e) => setUserArgument(e.target.value)}
                  placeholder={(() => {
                    const round = debateSession.current_round + 1
                    if (round === 1) {
                      return "💡 第一次辩论？没关系，从你的直觉开始！\n\n你可以这样思考：\n1. 先分析题目中的关键事实（谁、做了什么、结果如何）\n2. 从常识和逻辑角度思考（如果是我，我会怎么判断？）\n3. 说出你的想法，不用担心是否专业\n\n例如：\"我觉得这个情况应该...因为...\""
                    } else if (round === 2) {
                      return "💡 很好！继续深入思考\n\n你可以：\n1. 回应AI的质疑（你觉得AI说得有道理吗？）\n2. 补充更多事实细节\n3. 从不同角度思考问题\n\n如果提到了法律概念，可以简单解释一下你的理解"
                    } else {
                      return "💡 你已经很有思路了！\n\n可以尝试：\n1. 回应AI的质疑，完善你的论证\n2. 如果知道相关法律，可以提及（不知道也没关系）\n3. 用逻辑推理连接事实和结论\n\n记住：重点是思考过程，不是完美答案"
                    }
                  })()}
                  rows={6}
                  maxLength={1000}
                />
                <div className="input-footer">
                  <span className="char-count">{userArgument.length} / 1000</span>
                  <button
                    className="submit-argument-button"
                    onClick={submitArgument}
                    disabled={!userArgument.trim() || isSubmitting}
                  >
                    {isSubmitting ? '提交中...' : '提交论点'}
                  </button>
                </div>
                {/* 初学者友好提示 */}
                {debateSession.current_round === 0 && (
                  <div className="beginner-tip" style={{
                    marginTop: '10px',
                    padding: '10px',
                    background: '#e3f2fd',
                    borderRadius: '8px',
                    fontSize: '0.9rem',
                    color: '#1976d2'
                  }}>
                    💡 <strong>新手提示：</strong>不用担心不知道具体法条，先从分析事实和逻辑开始。AI会引导你逐步思考，帮助你建立法律思维。
                  </div>
                )}
              </label>
            </div>
          )}
        </div>
      )}

      {/* 评估阶段 */}
      {phase === 'evaluation' && evaluation && debateSession && (
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="evaluation-container"
        >
          <div className="evaluation-header">
            <h2>🎯 辩论评估</h2>
            <p className="evaluation-summary">{evaluation.summary}</p>
          </div>

          <div className="evaluation-scores">
            <div className="score-card">
              <div className="score-label">论证质量</div>
              <div className={`score-value ${evaluation.argument_quality >= 80 ? 'high' : evaluation.argument_quality >= 60 ? 'medium' : 'low'}`}>
                {evaluation.argument_quality}
              </div>
            </div>
            <div className="score-card">
              <div className="score-label">逻辑严谨性</div>
              <div className={`score-value ${evaluation.logical_rigor >= 80 ? 'high' : evaluation.logical_rigor >= 60 ? 'medium' : 'low'}`}>
                {evaluation.logical_rigor}
              </div>
            </div>
            <div className="score-card">
              <div className="score-label">法律准确性</div>
              <div className={`score-value ${evaluation.legal_accuracy >= 80 ? 'high' : evaluation.legal_accuracy >= 60 ? 'medium' : 'low'}`}>
                {evaluation.legal_accuracy}
              </div>
            </div>
          </div>

          <div className="evaluation-details">
            <div className="detail-section">
              <h3>📊 详细数据</h3>
              <ul>
                <li>总轮次：{evaluation.total_rounds} 轮</li>
                <li>关键事实：{evaluation.key_facts_count} 个</li>
                <li>法律条文：{evaluation.legal_provisions_count} 个</li>
                <li>推理完整性：{evaluation.reasoning_completeness} 分</li>
              </ul>
            </div>

            {evaluation.improvement_suggestions.length > 0 && (
              <div className="detail-section">
                <h3>💡 改进建议</h3>
                <ul>
                  {evaluation.improvement_suggestions.map((suggestion, idx) => (
                    <li key={idx}>{suggestion}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>

          <div className="evaluation-actions">
            <button
              className="action-button primary"
              onClick={restartDebate}
            >
              🔄 重新开始
            </button>
            <button
              className="action-button"
              onClick={() => {
                if (onNavigate) {
                  onNavigate('training')
                }
              }}
            >
              📚 返回训练
            </button>
          </div>
        </motion.div>
      )}

      {/* 初始选择阶段 */}
      {phase === 'select' && !currentQuestion && (
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="debate-start"
        >
          <h2>辩论式法律思维训练</h2>
          <p className="description">
            通过辩论的方式训练你的法律思维，AI将扮演对手或法官角色，
            与你进行法律观点的交锋，帮助你提升论证能力和逻辑思维。
          </p>
          <button
            className="start-button"
            onClick={async () => {
              // 从训练中获取一个题目
              try {
                const session = await trainingApi.startSession(userId)
                const question = await trainingApi.getNextQuestion(session.session_id)
                setCurrentQuestion(question)
                setPhase('position')
              } catch (error) {
                console.error('获取题目失败:', error)
              }
            }}
            disabled={isLoading}
          >
            {isLoading ? '加载中...' : '开始辩论训练'}
          </button>
        </motion.div>
      )}
    </div>
  )
}

export default DebatePanel

